package com.oyb.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
@WebServlet(urlPatterns = "/code")
public class CodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //生成验证码(测试新增注释)111
        int width = 60 ;
        int height = 40 ;
        //创建一个BufferImage对象2222
        BufferedImage imge = new BufferedImage(60,40, BufferedImage.TYPE_INT_RGB);
        //获得图片的一个图层对象，在图层对象上绘制内容
        Graphics graphics = imge.getGraphics();
        //设置颜色
        graphics.setColor(Color.GREEN);
        //绘制矩形(验证码的矩形)
        graphics.fillRect(0,0,width,height);
        //绘制内容
        String code = createCode();
        //获取时间戳并存入事件到session
        HttpSession session = req.getSession();
        session.setAttribute("time",System.currentTimeMillis());
        //session
        session.setAttribute("biaoshi",code);
        //设置颜色
        graphics.setColor(Color.red);
        //设置文字样式
        graphics.setFont(new Font("微软雅黑", Font.BOLD, 20));
        graphics.drawString(code, (int)(width*0.1), (int)(height*0.7));
        //绘制10条干扰线
        graphics.setColor(Color.blue);
        for(int i = 0;i<10;i++){
            graphics.drawLine((int)(Math.random()*width), (int)(Math.random()*height),
                    (int)(Math.random()*width), (int)(Math.random()*height));
        }
        //将图片输出给页面的Img标签
        ImageIO.write(imge, "jpg", resp.getOutputStream());
    }
    private String createCode(){
        //1000-9999的随机数
        return (int)(Math.random()*9000+1000)+"";
    }
}
